//
//  sample.cpp
//  asyn
//
//  Created by Eduardo Poyart on 2/6/12.
//  Copyright (c) 2012 Eduardo Poyart. All rights reserved.
//

#include <iostream>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include "asyn.h"

using namespace std;

void serverUpdate(ANTcpServer* server);
void clientUpdate(ANTcpClient* client);

void serverUpdate(ANTcpServer* server)
{
    //cout << "server update" << endl;
    if (server->isDataReady())
    {
        cout << "Data ready" << endl;
        vector<char> dest;
        server->receiveCopy(dest);
        string s(dest.begin(), dest.end());
        cout << "Server received: " << s << " <-----" << endl;
    }
    if (rand() % 90 == 0)
    {
        cout << "Send" << endl;
        int sendData = rand() % 10;
        stringstream ss;
        ss << sendData;
        server->send(ss.str());
        cout << "Server sent: " << ss.str() << " ----->" << endl;
    }
}

void clientUpdate(ANTcpClient* client)
{
    //cout << "client update" << endl;
    if (client->isDataReady())
    {
        cout << "Data ready" << endl;
        vector<char> dest;
        client->receiveCopy(dest);
        string s(dest.begin(), dest.end());
        cout << "-----> Client received: " << s << endl;
    }
    if (rand() % 90 == 0)
    {
        cout << "Send" << endl;
        int sendData = rand() % 10;
        stringstream ss;
        ss << sendData;
        client->send(ss.str());
        cout << "<----- Client sent: " << ss.str() << endl;
    }
}


int main(int argc, const char * argv[])
{
    srand((unsigned int)(time(0)%100000));
    
    bool is_server = false;
    if (argc < 3)
        exit(1);
    string s(argv[1]);
    if (s == string("server"))
        is_server = true;
    
    ANManager manager;
    
    if (is_server)
    {
        cout << argv[0] << " " << argv[1] << " " << argv[2] << endl;
        int port = atoi(argv[2]);
        cout << "Mode: server, port " << port << endl;
        ANTcpServer server(&manager, port, 128);
        cout << "Server started" << endl;
        while(1)
        {
            manager.update();
            if (server.isConnected())
                serverUpdate(&server);
            usleep(1000 * 1000 / 30);
        }    
    }
    else
    {
        if (argc < 4)
            exit(1);
        cout << argv[0] << " " << argv[1] << " " << argv[2] << " " << argv[3] << endl;
        cout << "Mode: client, connecting to " << argv[2] << ", port " << argv[3] <<  endl;
        ANTcpClient client(&manager, argv[2], argv[3], 128);
        cout << "Connected to server" << endl;
        while(1)
        {
            manager.update();
            if (client.isConnected())
                clientUpdate(&client);
            usleep(1000 * 1000 / 30);
        }
    }
    return 0;
}

